package game;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class LevelManager {

	private HashMap<String, Level> levelMap;
	private List<List<String>> levelLists;
	
	private Level currentLevel;

	public LevelManager() {
		levelMap = new HashMap<String, Level>();
		levelLists = new ArrayList<List<String>>();
	}

	public void load(File directory) throws JDOMException, IOException, ClassNotFoundException {
		levelLists.clear();
		File file = new File(directory, "worlds.xml");
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(file);
		Element root = doc.getRootElement();
		if (!root.getName().equals("worlds")) {
			throw new LevelBuildingException(
					"Expected 'worlds' as root element");
		}
		for (Element world : root.getChildren("world")) {
			String worldName = world.getAttributeValue("name");
			if (worldName == null || worldName.isEmpty()) {
				throw new LevelBuildingException("World name is empty!");
			}
			List<String> levelList = new ArrayList<String>();
			for (Element levelElement : world.getChildren("level")) {
				String levelSrc = levelElement.getAttributeValue("src");
				if (levelSrc == null || levelSrc.isEmpty()) {
					throw new LevelBuildingException("Level source is empty");
				}
				if (!levelMap.containsKey(levelSrc)) {
					LevelBuilder levelBuilder = new LevelBuilder(new File(directory, levelSrc));
					Level level = levelBuilder.createLevel();
					levelMap.put(levelSrc, level);
				}
				levelList.add(levelSrc);
			}
			levelLists.add(levelList);
		}
	}
	
	public void enterLevel(String level) {
		if(levelMap.containsKey(level)) {
			currentLevel = levelMap.get(currentLevel);
			currentLevel.reset();
		}
	}



}
